﻿using System.Collections.Generic;
using System.Web.Mvc;
using BSU.CSCE.Data.Model;
using BSU.CSCE.Utilities;
using BSU.CSCE.Web.Models;

namespace BSU.CSCE.Web.Controllers
{
    [HandleError]
    public class PublicationsController : BaseController
    {
        //public ActionResult Index(int? page)
        //{
        //    int pageSize = _configuration.ListPageSize;
        //    int pageNumber = page ?? 1;
        //    int totalCount;

        //    var orderby = Reflector.GetPropertyName<Publication>(x => x.PublishingTime);
            
        //    var publications = new List<Publication>();

            
        //        publications = _administrator.ListPublishedPublications("", orderby, false, pageSize * (pageNumber - 1), pageSize,
        //                                         out totalCount);

        //    var pagerModel = new PagerViewModel(totalCount, _configuration.ListPageSize, pageNumber);
        //    var listModel = new ListViewModel<Publication>(publications, pagerModel);

        //    return View(listModel);
        //}

        public ActionResult List(int? page, PublicationType type)
        {
            int pageSize = _configuration.ListPageSize;
            int pageNumber = page ?? 1;
            int totalCount;

            var orderby = Reflector.GetPropertyName<Publication>(x => x.PublishingTime);

            var publications = _administrator.ListPublishedPublications(type, orderby, false, pageSize * (pageNumber - 1), pageSize,
                                             out totalCount);

            var pagerModel = new PagerViewModel(totalCount, _configuration.ListPageSize, pageNumber);
            var listModel = new ListViewModel<Publication>(publications, pagerModel);

            return View(listModel);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Create()
        {
            var publication = new Publication
            {
                Status = PublicationStatus.Active,
                Type = PublicationType.ForMainPage
            };
            return GetCreatePublicationFormViewModel(publication);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create([Bind(Exclude = "Id")] Publication publication)
        {
            try
            {
               //user.AuthorId = CurrentSession.CurrentUser.Id;
                publication = _administrator.CreatePublication(publication);
                return RedirectToAction("Details", new { id = publication.Id });
            }
            catch
            {
               //ModelState.PopulateWithErrors(ex, ValueProvider);
                return GetCreatePublicationFormViewModel(publication);
            }
        }

        private ActionResult GetCreatePublicationFormViewModel(Publication publication)
        {
            return View(new CreatePublicationFormViewModel(publication));
        }
    }
}
